package org.finesys.samples.file.aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel clientChannel;

    public ReadCompletionHandler(AsynchronousSocketChannel clientChannel) {
        this.clientChannel = clientChannel;
    }


    @Override
    public void completed(Integer result, ByteBuffer attachment) {

        if (result == -1) {
            System.out.println("客戶端断开");
            try {
                clientChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        //当读取完成时反转缓冲区并打印
        attachment.flip();
        byte[] bytes = new byte[attachment.remaining()];
        attachment.get(bytes);
        System.out.println("收到消息：" + new String(bytes, StandardCharsets.UTF_8));
        attachment.clear();
        //从磁盘读取输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入消息：");
        String message = scanner.nextLine();
        System.out.println();
        //写入到异步套接字通道
        clientChannel.write(ByteBuffer.wrap(message.getBytes()));
        //继续下次读取调用
        clientChannel.read(attachment, attachment, new ReadCompletionHandler(clientChannel));
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        if (exc instanceof ClosedByInterruptException) {
            System.out.println("客户端因中断而断开连接");
        } else if (exc instanceof AsynchronousCloseException) {
            System.out.println("正常断开");
        } else {
            exc.printStackTrace();
        }
    }
}
